﻿App.page({
	id: 'profile',
	url: '/page/profile',
	require: ['signalr', 'alert', 'user'],
	init: function () {
		var $cont = $('.page-container'),
			$startSpeedGame = $('#startSpeedGame'),
			$createNewRoom = $('#createNewRoom'),
			$connectToRoom = $('#connectToRoom'),
			$startNewRoom = $('#startNewRoom'),
			$roomId = $('#roomId'),
			roomIdLength = 5,
			origin = '{0}//{1}/'.replace('{0}', window.location.protocol).replace('{1}', window.location.host),
			roomId = randomId(roomIdLength),
			urlForRoom = origin + roomId,
			$newRoomId = $('#newRoomId').val(urlForRoom),
			$name = $('#name'),
			$editName = $('#editName');

		delete App.user.roomId;

		App.ready(function () {
			$(document.body).removeAttr('style');

			if ($cont.css('opacity') == 0) {
				TweenMax.set($cont, { scale: 0.5 });
				TweenMax.set($cont, { scale: 1 });
				TweenMax.to($cont, 0.5, { opacity: 1 });
			}

			var urlRoomId = extractRoomId(window.location.href);
			if (urlRoomId != '') {
				$roomId.val(urlRoomId);
				$connectToRoom.click();
			}

			var client = new ZeroClipboard(document.getElementById('copy'));

			client.on('copy', function () {
				client.setText($newRoomId.val());
				App.alert.info(Localization.RoomIdAddedToClipboard);
			});
		});

		$newRoomId.on('keyup', function (e) {
			var code = e.keyCode || e.which;
			if (code == 13) {
				e.preventDefault();
				$newRoomId.trigger('blur');
				$startNewRoom.trigger('click');
				return false;
			}
			return true;
		});

		$roomId.on('keyup', function (e) {
			var code = e.keyCode || e.which;
			if (code == 13) {
				e.preventDefault();
				$roomId.trigger('blur');
				$connectToRoom.trigger('click');
				return false;
			}
			return true;
		});

		$roomId.bind('input propertychange', function() {
			$roomId.val(extractRoomId($roomId.val()));
		});

		$startSpeedGame.click(function () {
			start(init);
		});

		$createNewRoom.click(function () {
			var $parent = $createNewRoom.parent();
			$parent.height($parent.height()).css('opacity', 0);
			$startNewRoom.parent().removeClass('uk-hidden');
			$createNewRoom.hide();

			TweenMax.to($newRoomId.parent(), 0.5, {
				className: 'uk-width-3-5',
				onStart: function () { $parent.css('opacity', 1); $newRoomId.select(); }
			});

			TweenMax.to($startNewRoom, 0.5, {
				className: $startNewRoom.prop('class').replace('uk-width-1-1', 'uk-width-2-5'),
				onComplete: function () { $newRoomId.select(); }
			});
		});

		$startNewRoom.click(function () {
			App.user.roomId = roomId;
			start(createRoom);
		});

		$connectToRoom.click(function () {
			var id = $roomId.val();
			if (validateRoomId(id)) {
				App.user.roomId = id;
				$('#overlay').show();
				Ajax.post({
					url: '/checkRoom',
					data: {
						roomId: id,
						__RequestVerificationToken : App.getVerificationToken()
					},
					json: true,
					done: function (r) {
						r.success ? start(init) : roomNotExists();
					}
				});
			} else {
				$roomId.select().addClass('uk-form-danger');
				TweenMax.to($roomId, 1, { className: '-=uk-form-danger', delay: 1 });
			}
		});

		$newRoomId.on('keyup keypress change click', function (e) {
			e.preventDefault();
			$newRoomId.val(urlForRoom).prop('readonly', 'readonly').select();
			return false;
		});

		$roomId.click(function () {
			$roomId.select();
		});

		$name.click(function () {
			var p = $name.closest('.uk-clearfix');
			p.height(p.height());
			$name.hide();
			$editName.show().select();
		});

		$editName.bind('keyup', function (e) {
			var code = e.keyCode || e.which;
			if (code == 13) {
				e.preventDefault();
				$editName.trigger('blur');
				return false;
			}
			return true;
		});

		$editName.blur(function () {
			var newName = $editName.val();

			if (newName != $name.text() && App.user.changeName(newName)) {
				$name.text(newName);
			}

			$name.closest('.uk-clearfix').removeAttr('style');
			$editName.hide();
			$name.show();
		});

		function start(callback) {
			$('#overlay').show();
			App.signalr.start().done(callback);
			App.ui.setUrl(origin + App.user.roomId);
		}

		function createRoom() {
			App.signalr.server({
				hub: 'gameHub',
				action: 'createRoom',
				data: App.user.roomId
			}).fail(function (e) {
				App.alert.warning(Localization.ConnectionError);
				console.log('profile.page.js', e);
			}).done(init);
		}

		function init() {
			App.signalr.server({
				hub: 'gameHub',
				action: 'initializeUser',
				data: App.user.name()
			}).fail(function (e) {
				App.alert.warning(Localization.ConnectionError);
				console.log('profile.page.js', e);
			}).done(function (r) {
				if (App.isUndefined(r)) return;
				App.goToPage('game');
			});
		}

		function roomNotExists() {
			$('#overlay').hide();
			App.alert.danger(Localization.RoomNotExists);
			App.ui.setUrl(origin);
		}

		function randomId(n) {
			var id = [], chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

			if (window.crypto && window.crypto.getRandomValues) {
				var array = new Uint32Array(5);
				window.crypto.getRandomValues(array);
				while (n--) id += chars.charAt(array[n] % 62);
			} else {
				while (n--) id += chars.charAt(Math.floor(Math.random() * 62));
			}
			return id;
		}

		function extractRoomId(str) {
			if (str === null || typeof str === 'undefined' || str === '') return '';

			if (str.indexOf('/') != -1) {
				var paths = str.split('/'),
					last = paths.length - 1;
				str = paths[last]+'';
			}

			return validateRoomId(str) ? str : '';
		}

		function validateRoomId(id) {
			return /^[A-z0-9]{0,}$/.test(id) && id.length == roomIdLength;
		}

		ZeroClipboard.config({ swfPath: '/Scripts/ZeroClipboard.swf' });
	}
});